<!--
 * @Description: 个人争先创优申请
 * @Author: oooh
 * @Date: 2024-04-26 19:45:39
 * @LastEditors: oooh
 * @LastEditTime: 2024-06-21 11:56:42
 * @FilePath: \Civil_Servant_Performance_PC\src\views\work\annual-honor\index.vue
-->
<template>
  <div class="app-container">
    <div class="text-banner">
      <span>年度荣誉奖励</span>
      <el-button class="ml-10" size="mini" type="primary" circle icon="el-icon-refresh" plain @click="handleRefresh" />
    </div>
    <!-- 上传提示 -->
    <div class="el-upload__tip">
      <p>
        <b style="color: #f56c6c">*依据材料：</b>大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> 格式为
        <b style="color: #f56c6c">{{ fileType.join('/') }}</b
        >的文件（不超过<b style="color: #f56c6c">{{ limit }}</b
        >项）
      </p>
    </div>
    <el-table :data="tableList" border style="width: 100%" v-loading="tableLoading">
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="获得荣誉日期" prop="matterDate" width="160" align="center">
        <template slot-scope="scope">
          <el-date-picker
            v-if="!checkWorkPlanDisabled(scope.row.auditStatusDict)"
            v-model="scope.row.matterDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="获得荣誉日期"
          >
          </el-date-picker>
          <span v-else>{{ scope.row.matterDate || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="荣誉类型" prop="honorTypeDict" min-width="180" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-select v-if="!checkWorkPlanDisabled(scope.row.auditStatusDict)" v-model="scope.row.honorTypeDict" placeholder="请选择评优类型">
            <el-option v-for="item in dict.type.biz_personal_year_honor_type" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <dict-tag v-else :options="dict.type.biz_personal_year_honor_type" :value="scope.row.honorTypeDict" />
        </template>
      </el-table-column>
      <el-table-column label="说明描述" prop="describe" min-width="180" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="!checkWorkPlanDisabled(scope.row.auditStatusDict)"
            v-model="scope.row.describe"
            type="textarea"
            placeholder="输入说明描述"
            :rows="1"
            :autosize="{ minRows: 1, maxRows: 5 }"
          ></el-input>
          <span v-else>{{ scope.row.describe || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="依据材料" align="center" min-width="120">
        <template slot-scope="scope">
          <FileUpload
            v-if="!checkWorkPlanDisabled(scope.row.auditStatusDict)"
            v-model="scope.row.materialUrls"
            :isShowTip="false"
            :fileType="fileType"
          ></FileUpload>
          <div v-else>
            <div v-if="scope.row.materialUrls">
              <el-tooltip
                v-for="(url, index) in scope.row.materialUrls.split(',')"
                :key="index"
                effect="dark"
                :content="formatFileUrl(url)['name']"
                placement="top-start"
              >
                <el-button type="text" @click="handlePreviewFile(url)" class="file-preview-btn">
                  {{ formatFileUrl(url)['name'] }}
                </el-button>
              </el-tooltip>
            </div>
            <span v-else>-</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="申请日期" prop="applyDate" width="160" align="center">
        <template slot-scope="scope">
          <el-date-picker
            v-if="!checkWorkPlanDisabled(scope.row.auditStatusDict)"
            v-model="scope.row.applyDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
          <span v-else>{{ scope.row.applyDate || '-' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="申请人" prop="civilServantName" min-width="100" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="所属站办所" prop="deptName" min-width="140" align="center" show-overflow-tooltip></el-table-column> -->
      <el-table-column prop="name" label="操作" align="center" width="140" fixed="right">
        <template slot-scope="scope">
          <div>
            <el-button
              type="text"
              v-show="checkBtnVisible('revocation', scope.row.auditStatusDict)"
              class="color-warning"
              size="mini"
              @click.stop="handleWorkPlanRevocation(scope.row, 'centerWork')"
              v-hasPermi="['work:annual-honor:revocation']"
            >
              [审核中]点击撤回
            </el-button>

            <ApprovalLog :biz-id="scope.row.id" v-show="checkBtnVisible('finish', scope.row.auditStatusDict)">
              <el-button type="text" size="mini" class="color-success" icon="el-icon-check">[审核通过]</el-button>
            </ApprovalLog>

            <ApprovalLog
              :biz-id="scope.row.id"
              v-show="checkBtnVisible('resubmit', scope.row.auditStatusDict)"
              v-hasPermi="['work:annual-honor:submit']"
            >
              <el-button
                type="text"
                icon="el-icon-warning-outline"
                size="mini"
                @click.stop="handleWorkPlanSaveOrSubmit(scope.row, 'submit')"
                class="color-danger"
              >
                [被退回]重新提交
              </el-button>
            </ApprovalLog>

            <el-button
              type="text"
              v-show="checkBtnVisible('approval', scope.row.auditStatusDict, scope.row.submitMark)"
              size="mini"
              class="color-warning"
              v-hasPermi="['work:annual-honor:save']"
            >
              [审核中]
            </el-button>
            <el-button
              type="text"
              v-show="checkBtnVisible('save', scope.row.auditStatusDict, scope.row.submitMark)"
              size="mini"
              @click.stop="handleWorkPlanSaveOrSubmit(scope.row, 'save')"
              v-hasPermi="['work:annual-honor:save']"
            >
              保存
            </el-button>

            <el-button
              type="text"
              v-show="checkBtnVisible('submit', scope.row.auditStatusDict, scope.row.submitMark)"
              size="mini"
              @click.stop="handleWorkPlanSaveOrSubmit(scope.row, 'submit')"
              v-hasPermi="['work:annual-honor:submit']"
            >
              提交
            </el-button>
            <el-button
              type="text"
              v-show="scope.row.id && checkBtnVisible('remove', scope.row.auditStatusDict, scope.row.submitMark)"
              size="mini"
              @click.stop="handleWorkPlanRemove(scope.$index, scope.row)"
              v-hasPermi="['work:annual-honor:remove']"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <FilePreview :visible.sync="filePreviewVisible" :file="previewFile"></FilePreview>
  </div>
</template>

<script>
import FileUpload from '@/components/FileUpload'
import FilePreview from '@/components/FilePreview'
import { list, revocation, remove, add as addPlan, update as updatePlan } from '@/api/work/annual-honor'
import dayjs from 'dayjs'
import { mixins } from '@/mixins'
import ApprovalLog from '@/components/ApprovalLog'

export default {
  name: 'work_annual-honor',
  mixins: [mixins],
  dicts: ['biz_personal_year_honor_type'],
  props: {},
  components: { FileUpload, FilePreview, ApprovalLog },
  data() {
    return {
      filePreviewVisible: false,
      previewFile: {},
      // 部门树选项
      deptOptions: [],
      tableLoading: false,
      tableList: [],
      tableItem: {
        matterDate: undefined,
        honorTypeDict: undefined,
        describe: undefined,
        materialUrls: undefined,
        applyDate: dayjs().format('YYYY-MM-DD')
      },
      mapping: {
        matterDate: '获得荣誉日期',
        honorTypeDict: '荣誉类型',
        describe: '说明描述',
        applyDate: '申请日期'
      },
      queryParams: {}
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getList()
  },
  methods: {
    // 预览文件
    handlePreviewFile(url) {
      let fileItem = this.formatFileUrl(url)
      this.previewFile = { url, ...fileItem }
      this.filePreviewVisible = true
    },
    // 审核提示内容格式输出
    aduitContentFormat(raw) {
      let content = []
      content.push(`<p>审核意见：${raw.auditRemark || ' - '}</p>`)
      content.push(`<p>审核时间：${raw.auditTime || ' - '}</p>`)
      return content.join('')
    },
    // 校验按钮显示
    // 功能类型、审核状态、提交状态
    checkBtnVisible(type, audit, submit) {
      switch (type) {
        case 'approval':
          // 审核中
          return audit === 'SHZ'
        case 'revocation':
          // 撤回
          return audit === 'DSH'
        case 'submit':
          // 提交
          return !submit && audit !== 'SHBTG'
        case 'save':
        case 'remove':
          // 保存 && 删除
          return !submit
        case 'resubmit':
          // 退回重新提交
          return audit === 'SHBTG'
        case 'finish':
          // 审核通过
          return audit === 'SHTG'
        default:
          break
      }
    },
    // 校验工作计划表单字段是否可填
    checkWorkPlanDisabled(audit) {
      if (audit === 'SHTG' || audit === 'DSH' || audit === 'SHZ') {
        return true
      }
      return false
    },
    // 工作删除
    handleWorkPlanRemove(index, raw) {
      let removeContent = `您正在删除第 【${index + 1}】 项申请`
      this.$confirm(`${removeContent}，数据删除后将无法找回，请确认删除`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            const loading = this.$loading({
              target: '.el-message-box',
              lock: true,
              text: '正在删除...',
              spinner: 'el-icon-loading',
              background: 'rgba(255,255,255,0.6)'
            })
            remove({ id: raw.id })
              .then(() => {
                loading.close()
                this.getList()
                this.$modal.msgSuccess('已删除')
                done()
              })
              .catch(() => {
                loading.close()
                done()
              })
          } else {
            done()
          }
        }
      })
    },
    // 工作计划保存或提交校验
    handleWorkPlanSaveOrSubmitCheck(raw, operation) {
      for (let key of Object.keys(this.mapping)) {
        if (!raw[key]) {
          this.$message.error(`操作失败，【${this.mapping[key]}】 不能为空！`)
          return
        }
      }

      let mustItem = { submitMark: false }
      if (operation === 'submit') mustItem.submitMark = true
      let params = {}
      if (raw.id) params.id = raw.id
      // 根据工作类型填充对应参数
      for (let key of Object.keys(this.tableItem)) {
        mustItem[key] = raw[key]
      }
      params = { ...params, ...mustItem }
      return params
    },
    // 工作计划保存或提交
    async handleWorkPlanSaveOrSubmit(raw, operationType = 'save') {
      let params = await this.handleWorkPlanSaveOrSubmitCheck(raw, operationType)
      if (!params) return

      if (raw.id) {
        // 更新
        await updatePlan(params).then(res => {
          if (operationType === 'save') {
            this.$modal.msgSuccess('已更新')
          } else if (operationType === 'submit') {
            this.$modal.msgSuccess('已提交')
          }
        })
      } else {
        // 新增
        await addPlan(params).then(res => {
          if (operationType === 'save') {
            this.$modal.msgSuccess('已添加')
          } else if (operationType === 'submit') {
            this.$modal.msgSuccess('已提交')
          }
        })
      }

      this.getList()
    },
    // 工作计划撤回
    handleWorkPlanRevocation(raw, workType) {
      revocation({ id: raw.id }).then(res => {
        this.$modal.msgSuccess('已撤回')
        this.getList()
      })
    },
    handleRefresh() {
      this.getList()
    },
    getList() {
      this.tableLoading = true
      list(this.queryParams)
        .then(res => {
          this.tableLoading = false
          this.tableList = res.rows
          this.tableList.unshift(JSON.parse(JSON.stringify(this.tableItem)))
        })
        .catch(err => {
          this.tableLoading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: auto;
}

::v-deep .el-input-number--medium {
  width: auto;
}

::v-deep .el-button [class*='el-icon-'] + span {
  margin-left: 0;
}
</style>
